import { ref } from "vue";
import { defineStore } from "pinia";
import { LocalUser } from "@/users/local-user";
import { UserManager } from "@/users";

export const useUserStore = defineStore("user", () => {
  const isLogin = ref(false);

  // vue 应用程序启动时，设置用户登录状态
  async function setLoginStatusAsync() {
    const token = await getAccessTokenAsync();

    if (token != null) {
      isLogin.value = true;
    }
  }

  // 清除登录状态
  function cleanLoginStatus() {
    isLogin.value = false;
    LocalUser.cleanUserInfo();
  }

  async function getAccessTokenAsync() {
    let currentUser = LocalUser.tryGetUserInfo();

    if (currentUser != null) {
      // 如果用户过期，刷新访问令牌
      if (currentUser.isExpired()) {
        currentUser = await UserManager.refreshTokenAsync(currentUser.getRefreshToken());
        LocalUser.setUserInfo(currentUser);
      }

      const token = currentUser.getAccessToken();
      return currentUser.tokenInfo.token_type + " " + token;
    } else {
      return null;
    }
  }

  return { isLogin, getAccessTokenAsync, setLoginStatusAsync, cleanLoginStatus };
});
